package me.xuym.crawler.simpleextension.filter;

import com.cbs.java.component.application.Application;
import me.xuym.crawler.Processor;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by broche on 16/08/2017.
 */
public class SimpleWhiteListFilter extends Processor<List<SimpleWhiteFilterInput>, List<SimpleWhiteFilterInput>> {
    private List<String> whiteKeys = new ArrayList<>();

    public SimpleWhiteListFilter(Application application, List<String> whiteKeys) {
        super(application);

        this.whiteKeys.addAll(whiteKeys);
    }

    @Override
    public List<SimpleWhiteFilterInput> onProcess(List<SimpleWhiteFilterInput> simpleWhiteFilterInputs) throws Exception {
        if (whiteKeys == null || whiteKeys.size() == 0) {
            return simpleWhiteFilterInputs;
        }

        List<SimpleWhiteFilterInput> result = new ArrayList<>();
        for (SimpleWhiteFilterInput input : simpleWhiteFilterInputs) {
            boolean isInWhite = false;
            for (String key : input.simpleWhiteFilterFields()) {
                if (isInWhite(key)) {
                    isInWhite = true;
                    break;
                }
            }
            if (isInWhite) {
                result.add(input);
            } else {
                // do nothing
            }
        }
        return result;
    }

    private boolean isInWhite(String key) {
        if (whiteKeys.size() > 0) {
            for (String tkey : whiteKeys) {
                if (key.contains(tkey)) {
                    return true;
                }
            }
            return false;
        } else {
            return true;
        }
    }
}
